# -*- coding: utf-8 -*-
# -------------------------------
# @文件：log.py
# @时间：2024/3/22 14:02
# @作者：caiweichao
# @功能描述：二次封装的日志类
# -------------------------------
import os
import shutil
import logging

from util.basic.times import Times
from util.basic.analysis_yaml import AnalysisYaml
from config import constants_path

# 读取日志配置
log_conf = AnalysisYaml().get_date('LOG_CONFIG')

# 创建日志收集器，定义日志数据级别
logger = logging.getLogger("Log")
logger.setLevel(log_conf['LOG_LEVEL'])


def set_handler(levels):
    if levels == 'error':  # 判断如果是error就添加error的handler
        logger.addHandler(Log.error_handle)
    else:  # 其他添加到infohandler
        logger.addHandler(Log.handler)
    logger.addHandler(Log.ch)  # 全部输出到console


def remove_handler(levels):
    if levels == 'error':
        logger.removeHandler(Log.error_handle)
    else:
        logger.removeHandler(Log.handler)
    logger.removeHandler(Log.ch)


# 获取当天的日志存放目录，不存在则创建，最大保存 n 天
class LogStoragerPocess:
    @staticmethod
    def get_log_dir():
        today = Times.custom_time('%Y%m%d')
        log_dir = str(os.path.join(constants_path.LOG_PATH, today))
        try:
            if not os.path.isdir(log_dir):
                os.makedirs(log_dir)
            # 删除超过n天的日志目录
            max_time = int(today) - log_conf['SAVE_DAY']
            for floder in os.listdir(constants_path.LOG_PATH):
                if max_time > int(floder):
                    shutil.rmtree(os.path.join(constants_path.LOG_PATH, floder))
        except FileExistsError:
            raise Exception("文件夹已经存在")
        finally:
            return log_dir


class Log:
    __obj = None

    @staticmethod
    def __new__(cls, *args, **kwargs):
        if not cls.__obj:
            cls.__obj = super().__new__(cls)
        return cls.__obj

    # 实例化文件管理类
    log_dir = LogStoragerPocess.get_log_dir()
    # 指定输出文件
    log_file = os.path.join(log_dir, 'logs.log')
    # 设置日志输出格式
    formatter = logging.Formatter(fmt=log_conf['FORMATTER'])
    # 指定输出渠道
    # 控制台输出
    ch = logging.StreamHandler()
    ch.setLevel("DEBUG")
    ch.setFormatter(formatter)
    # 文件日志输出
    handler = logging.FileHandler(filename=log_file, encoding='utf-8')
    handler.setLevel(log_conf.get("LOG_LEVEL_CONSILE"))
    handler.setFormatter(formatter)
    # 错误日志输出
    error_handle = logging.FileHandler(filename=log_file, encoding='utf-8')
    error_handle.setLevel('ERROR')
    error_handle.setFormatter(formatter)

    @staticmethod
    def debug(msg):
        set_handler('debug')
        logger.debug(msg)
        remove_handler('debug')

    @staticmethod
    def info(msg):
        set_handler('info')
        logger.info(msg)
        remove_handler('info')

    @staticmethod
    def error(msg):
        set_handler('error')
        # 同时输出异常信息
        logger.error(msg, exc_info=True)
        remove_handler('error')
